/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="gray-release__container">
        <div class="table-data">
            <sf-toolbar ref="toolbar">
                <sf-button
                    ref="addBtn"
                    class="creat-button btn-blank"
                    icon-cls="iconxinzeng2">
                    <lang>新增灰度发布</lang>
                </sf-button>
                <sf-layer ref="layer"
                          default-target="addBtn"
                          trigger="hover"
                          :default-width="200">
                    <div class="add-release__item"
                         @click="_addNewCompare">
                        <div class="add_release__title">
                            <lang>新版本对比发布</lang>
                        </div>
                        <div class="add_release__content">
                            <lang>新服务A和新服务B同时部署在同个环境中</lang>
                        </div>
                    </div>
                    <div class="add-release__item"
                         @click="_addOldCompare">
                        <div class="add_release__title">
                            <lang>新旧版对比发布</lang>
                        </div>
                        <div class="add_release__content">
                            <lang>新服务B部署在旧服务A的环境中</lang>
                        </div>
                    </div>
                </sf-layer>
                <sf-button
                    ref="submit"
                    class="creat-button btn-blank"
                    icon-cls="iconrefresh"
                    @click="_refresh">
                    <lang>刷新</lang>
                </sf-button>
                <sf-searchfield
                    v-model="searchParams.keyword"
                    class="pull-right"
                    :placeholder="_('请输入灰度服务名称')"
                    @trigger="_startSearch"
                    @clear="_startSearch" />
            </sf-toolbar>
            <empty-panel v-if="showEmptyGray"
                         :text="emptyText" />
            <div v-else
                 class="gray-release__box">
                <div v-for="(item,index) in abtestList"
                     :key="index"
                     class="gray-release-item">
                    <div class="gray-release-item__top">
                        <div class="left">
                            <div class="release-img">
                            </div>
                            <div class="release-title">
                                {{ item.readableName }}
                            </div>
                            <div class="release-type">
                                Web Service
                            </div>
                            <div class="release-url">
                                <i
                                    v-clipboard:copy="item.url"
                                    v-clipboard:success="_copySuccess"
                                    :title="_('复制URL')"
                                    class="iconfont icon iconrelation m-r5"></i>
                                <div class="name">
                                    URL：
                                </div>
                                <div class="release-url__text font-important">
                                    {{ item.url }}
                                </div>
                            </div>
                            <div class="line">
                                |
                            </div>
                            <div class="release-time">
                                <i class="iconfont icon icondengdaiyilaiwancheng  m-r5"></i>
                                <div class="name">
                                    <lang>开始时间：</lang>
                                </div>
                                <div class="release-time__text font-important">
                                    {{ encodeTime(item.createTime) }}
                                </div>
                            </div>
                        </div>
                        <div class="right">
                            <sf-button-primary
                                class="m-r15"
                                icon-cls="iconyunhangzhong1"
                                size="normalless"
                                @click="_addRelease(item)">
                                <lang>正式发布</lang>
                            </sf-button-primary>
                            <sf-button
                                class="m-r15"
                                icon-cls="iconsip-edit"
                                size="normalless"
                                @click="_grayDynamicExpansion(item)">
                                <lang>动态扩容</lang>
                            </sf-button>
                            <sf-button
                                class="m-r15"
                                icon-cls="icon-comp-delete"
                                size="normalless"
                                @click="_deleteService(item)">
                                <lang>删除</lang>
                            </sf-button>
                        </div>
                    </div>
                    <div class="gray-release-item__content">
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>服务1：</lang>
                            </div>
                            <div class="font-important flex">
                                {{ item.default.subName }}
                                <span
                                    class="current m-l5"
                                    :class="item.default.old?'old':'new'"></span>
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>模型：</lang>
                            </div>
                            <div class="font-important">
                                {{ item.default.modelName }}
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>服务状态：</lang>
                            </div>
                            <div
                                class="font-important common-status"
                                :class="serviceStatusClass(item.default.status)">
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>流量权重：</lang>
                            </div>
                            <div class="font-important">
                                {{ `${item.default.traffic}%` }}
                            </div>
                        </div>
                    </div>
                    <div class="gray-release-item__content">
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>服务2：</lang>
                            </div>
                            <div class="font-important flex">
                                {{ item.canary.subName }}
                                <span
                                    class="current m-l5"
                                    :class="item.canary.old?'old':'new'"></span>
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>模型：</lang>
                            </div>
                            <div class="font-important">
                                {{ item.canary.modelName }}
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>服务状态：</lang>
                            </div>
                            <div
                                class="font-important common-status"
                                :class="serviceStatusClass(item.canary.status)">
                            </div>
                        </div>
                        <div class="content-box">
                            <div class="content-box-name">
                                <lang>流量权重：</lang>
                            </div>
                            <div class="font-important">
                                {{ `${item.canary.traffic}%` }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>


import EmptyPanel from 'src/components/empty_panel';

import newCompareForm from '../label_form/new_compare_form.vue';

import oldCompareForm from '../label_form/old_compare_form.vue';

import releaseForm from '../label_form/release_form.vue';

import grayDynamicExpansion from '../label_form/gray_dynamic_expansion.vue';


import { encodeDate } from 'src/util/format';
import deployUrlAdapter from 'src/home/mod_common/deploy_url_adapter';

import {
    SERVICE_STATUS_NAME
} from '../const';



import {NEW_FORM_VALUE} from '../const';
import { deepClone } from 'src/util/deep_clone';

export default {
    name: 'GrayReleaseContainer',
    props:{
        modelList:{
            type:Array,
            default:()=>[]
        }
    },
    components:{
        EmptyPanel
    },
    data () {
        return {
            abtestList:[],
            searchParams:{
                projectId:'',
                keyword:''
            },

            imageList:[],
            emptyText:_('暂无灰度发布数据'),
            showEmptyGray:false
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        }
    },
    mounted () {
        this._getAbtestList();
    },
    methods: {
        _createGrayDynamicExpansion () {
            if (!this.grayDynamicExpansion) {
                this.grayDynamicExpansion = this.$modal(grayDynamicExpansion, {
                    autoDestory: true,
                    props: {}
                });
            }

            return this.grayDynamicExpansion;
        },

        _grayDynamicExpansion (record) {
            let formWin = this._createGrayDynamicExpansion();
            formWin.formRoot.setJsonValue(record);
            formWin.open({
                title: _('动态扩容'),
                submit:()=>{
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxGrayDynamicExpansion(ajaxParams, formWin);
                }
            });
        },

        // 动态扩容
        async ajaxGrayDynamicExpansion (params, formWin) {
            formWin.hide();
            this.$mask();
            const ABTEST_URLS_PATCH = deployUrlAdapter(`grayreleases/${params.id}`);
            let jsonData = await this.$ajax.patch(ABTEST_URLS_PATCH, params);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('动态扩容失败'));
            }
            this.$ok(_('动态扩容成功'));
            this._getAbtestList();
        },

        // 删除服务
        _deleteService (params) {
            let title = params.readableName;
            this.$confirm({
                title: _('确定'),
                subTitle: _('确定要删除{0}吗？', title),
                msg: _('删除后，相关的服务一同删除（不包括已经正式发布的<br/>服务），请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteService(params);
                    }
                }
            });
        },

        // 删除服务
        async ajaxDeleteService (params) {
            this.$mask();
            const ABTEST_URLS_DELETE = deployUrlAdapter(`grayreleases/${params.id}`);
            let jsonData = await this.$ajax.delete(ABTEST_URLS_DELETE, {id:params.id});
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }
            this.$ok(_('删除成功'));
            this._getAbtestList();
        },


        async refreshStatus () {
            let statusParams = deepClone(this.searchParams);
            Object.assign(statusParams, {withStatus:true});
            const ABTEST_URLS_GET = deployUrlAdapter(`projects/${this.projectId}/grayreleases`);
            let jsonData = await this.$ajax.get(ABTEST_URLS_GET, statusParams);
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.abtestList = data;
        },


        // 刷新grid
        async _getAbtestList () {
            this.$mask();
            this.searchParams.projectId = this.projectId;
            const ABTEST_URLS_GET = deployUrlAdapter(`projects/${this.projectId}/grayreleases`);
            let jsonData = await this.$ajax.get(ABTEST_URLS_GET, this.searchParams);
            this.$unmask();
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.abtestList = data;
            this.showEmptyGray = !data.length;
            this.refreshStatus();
        },

        // 旧版本对比
        _createOldCompareFormWin () {
            if (!this.oldCompareFormWin) {
                this.oldCompareFormWin = this.$modal(oldCompareForm, {
                    autoDestory: true
                });
            }

            return this.oldCompareFormWin;
        },
        async _addOldCompare () {
            let formWin = this._createOldCompareFormWin();
            const SIMPLE_MODEL_URL = deployUrlAdapter(`projects/${this.projectId}/simplegrayreleases`);
            let jsonData = await this.$ajax.get(SIMPLE_MODEL_URL, {projectId:this.projectId});
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            let modelNameList = data.map(item=>{
                return {
                    label:item.readableName,
                    value:item.id,
                    modelName:item.modelName
                };
            });

            formWin.open({
                reset: true,
                title: _('新旧版本对比发布'),
                data:{
                    imageList:this.imageList,
                    modelNameList,
                    modelList:this.modelList,
                    formData:{
                        canaryTrafficPercent:50,
                        id: '',
                        readableName:'',
                        protocol:1,
                        subModelService:{
                            cpuNum:1,
                            gpuNum:0,
                            memorySize:1,
                            minReplicas:1,
                            maxReplicas:1,
                            image:'',
                            modelUri:'',
                            modelName:'',
                            traffic:50,
                            subName:'',
                            modelId:''
                        }
                    }
                },
                submit:()=>{
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    const ABTEST_URLS_ADD = deployUrlAdapter(`services/${ajaxParams.id}/tograyrelease`);
                    this.ajaxSubmitReleaseCompare(ABTEST_URLS_ADD, ajaxParams, formWin);
                }
            });
        },

        // 新版本对比
        _createNewCompareFormWin () {
            if (!this.newCompareFormWin) {
                this.newCompareFormWin = this.$modal(newCompareForm, {
                    autoDestory: true,
                    props:{}
                });
            }

            return this.newCompareFormWin;
        },
        _addNewCompare () {
            let formWin = this._createNewCompareFormWin();
            formWin.open({
                reset: true,
                title: _('新版本对比发布'),
                data:{
                    modelList:this.modelList,
                    formData:deepClone({...NEW_FORM_VALUE})
                },
                submit:()=>{
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    ajaxParams.projectId = this.projectId;
                    const ABTEST_URLS_ADD = deployUrlAdapter(`projects/${this.projectId}/grayreleases`);
                    this.ajaxSubmitReleaseCompare(ABTEST_URLS_ADD, ajaxParams, formWin);
                }
            });
        },

        // 新增/编辑算法的卡片信息
        async ajaxSubmitReleaseCompare (url, params, formWin, fetch = 'post') {
            formWin.$mask();
            let jsonData = await this.$ajax[fetch](url, params);
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('保存失败'));
            }
            this.$ok(_('保存成功'));
            formWin.hide();

            await this._getAbtestList();
        },

        // 正式发布
        _createReleaseFormWin () {
            if (!this.releaseFormWin) {
                this.releaseFormWin = this.$modal(releaseForm, {
                    autoDestory: true
                });
            }

            return this.releaseFormWin;
        },
        _addRelease (record) {
            let formWin = this._createReleaseFormWin();
            let list = [{
                name:record.default.subName
            }, {
                name:record.canary.subName
            }];
            formWin.open({
                reset: true,
                title: _('正式发布'),
                data:{
                    list
                },
                submit:()=>{
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxSubmitFinishRelease(ajaxParams, record, formWin);
                }
            });
        },

        // 新增/编辑算法的卡片信息
        async ajaxSubmitFinishRelease (params, record, formWin) {
            formWin.$mask();

            let {id} = record;
            let url = params === 0 ?
                deployUrlAdapter(`grayreleases/${id}/selectdefault`) :
                deployUrlAdapter(`grayreleases/${id}/selectcanary`);
            let jsonData = await this.$ajax.patch(url, {id});
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('正式发布失败'));
            }
            this.$ok(_('正式发布成功'));
            formWin.hide();

            await this._getAbtestList();
        },


        encodeTime (time) {
            return encodeDate(time);
        },
        serviceStatusClass (status) {
            return `${SERVICE_STATUS_NAME[status]}`;
        },
        _startSearch () {
            this._getAbtestList();
        },
        _copySuccess () {
            this.$ok(_('复制URL成功'));
        },
         _refresh () {
            this._getAbtestList();
        }

    }
};


</script>
<style lang="less">
    .add-release__item{
        padding: 10px 15px;
        border-bottom:1px solid #E3E6EC;
        cursor: pointer;
        &:hover{
            background-color: #e8f0ff;
        }
        &:last-child{
            border-bottom: none;
        }
        .add_release__title{
            color: #14161A;
            font-weight:bolder;
            font-size:14px;
            margin-bottom:8px;
        }
    }
    .gray-release__container{
        height: 100%;
        .table-data{
            height: 100%;
        }
        .cluster-empty-panel,.cluster-empty-panel__container{
            height: calc(100% - 49px);
        }
        .gray-release__box{
            height: calc(100% - 50px);
            overflow: auto;

            .gray-release-item{
                padding-top: 32px;
                margin-left: 90px;
                border-bottom:1px solid  #E3E6EC;
                padding-bottom: 8px;
            }
            color: #707A89;
            .font-important{
                color: #14161A;
            }
            .gray-release-item__content{
                display: flex;
                margin-bottom: 15px;
                .content-box{
                    display: flex;
                    flex: 0.5;
                    .flex{
                        display: flex;
                    }
                }
            }
            .current{
                width: 32px;
                height: 18px;
                display: inline-block;
            }
            .new{
                background: url(../../../../img/service/new.svg);
                background-size: 100% 100%;
            }
            .old{
                background: url(../../../../img/service/old.svg);
                background-size: 100% 100%;
            }
            .common-status{
                width: 64px;
                display: inline-block;
                height: 18px;
                &.stopped{
                    background: url(../../../../img/service/stopped.svg);
                    background-size: 100% 100%;
                }
                &.ready{
                    background: url(../../../../img/service/ready.svg);
                    background-size: 100% 100%;
                }
                &.starting{
                    background: url(../../../../img/service/starting.svg);
                    background-size: 100% 100%;
                }
                &.failed{
                    background: url(../../../../img/service/failed.svg);
                    background-size: 100% 100%;
                }
            }

            .gray-release-item__top{
                display:flex;
                justify-content: space-between;
                margin-bottom: 20px;
                .left{
                    margin-left: -65px;
                    display:flex;
                    align-items:center;
                    .release-img{
                        width: 48px;
                        height: 48px;
                        margin-right: 16px;
                        background: url(../../../../img/service/run.svg);
                        background-size: 100% 100%;
                    }
                    .release-title{
                        font-size: 16px;
                        color: #14161A;
                        font-weight: bold;
                        margin-right: 8px;
                    }
                    .release-type{
                        background: #E8F0FF;
                        border: 1px solid #ADC9FF;
                        border-radius: 2px;
                        font-size: 12px;
                        color: #204ED9;
                        margin-right: 26px;
                        width: 86px;
                        height: 18px;
                        text-align: center;
                    }
                    .release-status{
                        background: #E8F0FF;
                        border: 1px solid #ADC9FF;
                        border-radius: 2px;
                        font-size: 12px;
                        color: #204ED9;
                        margin-right: 32px;
                        width: 52px;
                        height: 18px;
                        text-align: center;
                    }
                    .release-url,.release-time{
                        display: flex;
                        .iconrelation{
                            cursor: pointer;
                        }
                    }
                    .line{
                        width: 1px;
                        height: 10px;
                        margin: 0px 8px;
                        margin-top: -8px;
                    }
                }
            }
        }
    }
</style>
